<template>
  <main-card title="AI应用" :tabs="getTabs()" :online-lab="true" :show-screen-space="false">
    <div class="page w">
      <div class="page__top">
        <app-num :num-obj="numObj" :style-attr="styleAttr" />
        <call-overview />
      </div>
      <authorization-overview v-if="APIDataList" :api-data="APIDataList" :sdk-data="SDKDataList" :sdk-cache="SDKDataList" />
    </div>
  </main-card>
</template>

<script lang="ts" setup>
  import { onMounted, ref } from 'vue'

  import { overviewApi } from '@/services/api'

  import { getTabs } from '../utils'
  import AppNum from './components/AppNum.vue'
  import AuthorizationOverview from './components/AuthorizationOverview.vue'
  import CallOverview from './components/CallOverview.vue'

  const APIDataList = ref([])
  const SDKDataList = ref([])
  const numObj = ref({})
  const styleAttr = {
    '--online-width': '',
    '--offline-width': ''
  }
  // 获取数据
  const init = async (key: string): Promise<void> => {
    const { data } = await overviewApi.getOverview({
      serveType: key
    })

    APIDataList.value = data.apiVOList
    SDKDataList.value = data.sdkVOList
    numObj.value = {
      appCount: data.appCount,
      onlineActivationCount: data.onlineActivationCount,
      offlineActivationCount: data.offlineActivationCount
    }
    // 分母为0
    const denom = data.onlineActivationCount + data.offlineActivationCount
    if (denom === 0) {
      styleAttr['--online-width'] = '0%'
      styleAttr['--offline-width'] = '0%'
    } else {
      // 分母不为0时计算在线百分比
      styleAttr['--online-width'] =
        ((data.onlineActivationCount / (data.offlineActivationCount + data.onlineActivationCount)) * 100).toFixed(2) + '%'

      const resultOnline = parseFloat(styleAttr['--online-width'])

      if (Number.isInteger(resultOnline)) {
        styleAttr['--online-width'] = Math.round(resultOnline) + '%'
      } else {
        styleAttr['--online-width'] = resultOnline.toFixed(2) + '%'
      }

      // 分母不为0时计算离线百分比
      styleAttr['--offline-width'] =
        ((data.offlineActivationCount / (data.offlineActivationCount + data.onlineActivationCount)) * 100).toFixed(2) + '%'

      const resultOffline = parseFloat(styleAttr['--offline-width'])

      if (Number.isInteger(resultOffline)) {
        styleAttr['--offline-width'] = Math.round(resultOffline) + '%'
      } else {
        styleAttr['--offline-width'] = resultOffline.toFixed(2) + '%'
      }
    }
  }

  onMounted(() => {
    init('')
  })
</script>
<style lang="less" scoped>
  .page {
    display: flex;
    align-items: flex-start;
    padding: 0;
    flex-direction: column;
    gap: 24px;

    .page__top {
      display: flex;
      align-items: flex-start;
      gap: 24px;
      width: 100%;
    }
  }
</style>
